#include "drivers.h"
#include "rtos.h"


/**
 * @brief  Initialize PA0 as IRQ Input Key with preemption 
 *  	   priority 2 and subpriority 0(as sub priority is not
 *  	   used in this system by default),you will need to
 *  	   implement the EXTI_IRQHandler() as Interrupt Service
 *  	   Routine.
 *
 * @param   none
 * @return  none
 *
 */

void Key_Init(void)
{
	GPIO_InitTypeDef Key_InitStructure;
	EXTI_InitTypeDef EXTI_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);

	Key_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	Key_InitStructure.GPIO_Pin = GPIO_Pin_0;
	Key_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;

	GPIO_Init(GPIOA,&Key_InitStructure);

	GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource0);

	EXTI_InitStructure.EXTI_Line = EXTI_Line0;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;

	EXTI_Init(&EXTI_InitStructure);

	NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
	
	NVIC_Init(&NVIC_InitStructure);
}

/**
 * @brief  EXTI0 Interrupt Service Routine,this will give a 
 *  	   semaphore to release the related Task.
 *
 * @param   none
 * @return  none
 *
 * Reverse byte order in unsigned short value
 */

void EXTI0_IRQHandler(void)
{

	portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE; 

	xSemaphoreGiveFromISR(KeyTask_Ball,&xHigherPriorityTaskWoken);
	EXTI_ClearITPendingBit(EXTI_Line0);
	portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);

}
